package com.xl.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xl.yygh.cmn.client.DictFeignClient;
import com.xl.yygh.hosp.repository.HospitalRepository;
import com.xl.yygh.hosp.service.HospitalService;
import com.xl.yygh.model.enums.DictEnum;
import com.xl.yygh.model.model.hosp.Hospital;
import com.xl.yygh.model.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XiangLiang
 * @date 2023/10/24 14:12
 * @description
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Resource
    private HospitalRepository hospitalRepository;

    @Resource
    private DictFeignClient dictFeignClient;

    /**
     * 上传医院信息
     *
     * @param map 医院信息Map
     */
    @Override
    public void saveHospital(Map<String, Object> map) {
        // Object转Hospital实体
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(map), Hospital.class);
        // 通过HosCode获取对应Hospital实体
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        // 若实体存在，则修改
        if (null != targetHospital) {
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
        } else {
            // 实体不存在，添加
            // 0：未上线 / 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
        }
        hospital.setUpdateTime(new Date());
        hospital.setIsDeleted(0);
        hospitalRepository.save(hospital);
    }

    /**
     * 根据签名传回医院信息
     *
     * @param hoscode 医院编号
     */
    @Override
    public Hospital getHospital(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    /**
     * 获取分页列表
     *
     * @param page            当前页
     * @param limit           每页记录数
     * @param hospitalQueryVo 查询VO
     * @return 分页列表
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Pageable pageable = PageRequest.of(page - 1, limit);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        pages.getContent().stream().forEach(item -> {
            this.setHospParam(item);
        });
        return pages;
    }

    /**
     * 为hospital实体设置字典参数
     *
     * @param hospital hospital实体
     * @return 设置完参数的hospital实体
     */
    private Hospital setHospParam(Hospital hospital) {
        String hostype = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String provinceName = dictFeignClient.getName(hospital.getProvinceCode());
        String cityName = dictFeignClient.getName(hospital.getCityCode());
        String districtName = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("hostype", hostype);
        hospital.getParam().put("fullAddress", provinceName + cityName + districtName);

        return hospital;
    }

    /**
     * 更新上线状态
     *
     * @param id     医院id
     * @param status 状态（0：未上线 / 1：已上线）
     */
    @Override
    public void updateStatus(String id, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 获取医院详情
     *
     * @param id 医院ID
     * @return 医院详情和排班情况
     */
    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();

        Hospital hospital = this.setHospParam(hospitalRepository.findById(id).get());
        result.put("hospital", hospital);

        // 单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        // 不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    /**
     * 获取医院名称
     *
     * @param hoscode 医院编号
     * @return 医院名称
     */
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital != null) {
            return hospital.getHosname();
        }
        return null;
    }

    /**
     * 根据医院名称查询
     *
     * @param hosname 医院名称
     * @return 医院信息List
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    /**
     * 根据医院编号获取医院预约挂号详情
     *
     * @param hoscode 医院编号
     * @return 医院预约挂号详情
     */
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        // 医院详情
        Hospital hospital = this.setHospitalHosType(this.getHospital(hoscode));
        result.put("hospital", hospital);
        // 预约规则
        result.put("bookingRule", hospital.getBookingRule());
        // 不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    /**
     * 获取查询list集合，遍历进行医院等级封装
     *
     * @param hospital Hospital实体
     * @return 医院等级封装后的Hospital实体
     */
    private Hospital setHospitalHosType(Hospital hospital) {
        // 根据dictCode和value获取医院等级名称
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        // 查询省 市  地区
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("fullAddress", provinceString + cityString + districtString);
        hospital.getParam().put("hostypeString", hostypeString);
        return hospital;
    }
}
